/**
 *  iic_eeprom.c - A iic eeprom device driver.
 *
 *  Copyright (C) 2008-2010 ZhangHu
 *  All rights reserved.
 *  E-MAIL: anmnmnly@gmail.com
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
#include "include/types.h"
#include "include/sem.h"
#include "drivers/chdev.h"
#include "drivers/iic_eeprom.h"

#include "devs.h"


extern void set_iic_eeprom_mode(bool_t master_mode);
extern uint32 get_iic_eeprom_size(void);
extern void init_iic_eeprom(void);
extern bool_t iic_eeprom_write_byte(uint32 addr, char_t data);
extern char_t iic_eeprom_read_byte(uint32 addr, int32 *err);



static int32 iic_eeprom_write(const char_t *buf, uint32 len, loff_t loff)
{
    uint32 i = 0;
    for(; i<len; i++) {
        if(!iic_eeprom_write_byte(loff++, buf[i])) {
            break;
        }
    }

	return(i);
}




static int32 iic_eeprom_read(char_t *buf, uint32 len, loff_t loff)
{
    int32 err = -1;
    uint32 i = 0;
    uchar_t ch = 0;

    for(; i<len; i++) {
        ch = iic_eeprom_read_byte(loff++, &err);
        if(err == 1) {
            buf[i] = ch;
        } else {
            break;
        }
    }

	return(i);
}



static int32 iic_eeprom_ioctl(uint32 cmd, void *arg)
{
    if(cmd != (uint32)IIC_CMD_CHGMODE) {
        return(-1);
    }

    return(0);
}



struct chdev_operations iic_eeprom_op = {
    NULL,
    NULL,
    iic_eeprom_write,
    iic_eeprom_read,
    iic_eeprom_ioctl,
    NULL
};



void iic_eeprom_register(void)
{
    init_iic_eeprom();
    set_iic_eeprom_mode(TRUE);

    chdevRegister(IIC_ID, IIC_EEPROM_ID, IIC_EEPROM,
                  get_iic_eeprom_size(), &iic_eeprom_op);
}

